<script setup>
import { ref, onMounted, watchEffect, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { statistics3Api } from '@/api/index'

const options = [
  {
    text: '近1个月',
    value: 'month'
  },
  {
    text: '近1周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  }
]

//默认选中
const checked = ref('hour')
//改变选中及获取选中数据
const onChange = async (val) => {
  checked.value = val
  getstatistics3()
}

//获取数据
const statistics3List = ref({})
const getstatistics3 = async () => {
  const res = await statistics3Api(checked.value)
  statistics3List.value = res
}

//获取dom
const chartRef = ref(null)
let myChart = null

onMounted(() => {
  //调用接口获取数据
  getstatistics3()

  // 基于准备好的dom，初始化echarts实例
  myChart = echarts.init(chartRef.value)
  // 绘制图表（watchEffect追踪数据变化）
  watchEffect(() => {
    myChart.setOption({
      xAxis: {
        data: statistics3List.value.x
      },
      yAxis: {},
      series: [
        {
          name: '销量',
          type: 'bar',
          data: statistics3List.value.y
        }
      ]
    })
  })

  //监听屏幕变化改变myChart尺寸
  window.addEventListener('resize', () => {
    myChart.resize()
  })
})

//移除屏幕监听
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    myChart.resize()
  })
})
</script>
<template>
  <el-card shadow="never" class="mt-4">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">订单统计</span>
        <div>
          <el-check-tag
            style="margin-right: 8px"
            v-for="(item, index) in options"
            :key="index"
            :checked="checked === item.value"
            @click="onChange(item.value)"
            >{{ item.text }}</el-check-tag
          >
        </div>
      </div>
    </template>
    <div ref="chartRef" style="width: 100%; height: 300px"></div>
  </el-card>
</template>
